#include "purchaseordercreate.h"
#include "ui_purchaseordercreate.h"
#include <QMessageBox>

PurchaseOrderCreateWindow::PurchaseOrderCreateWindow(QWidget *parent)
    : QWidget(parent)
    , purchaseordercreatewindowUi(new Ui::PurchaseOrderCreateWindow)
    , networkManager(new NetworkManager(this))
{
    purchaseordercreatewindowUi->setupUi(this);

    connect(networkManager, &NetworkManager::createPurchaseOrderResponseReceived, this, &PurchaseOrderCreateWindow::handleCreatePurchaseOrderResponse);
}

PurchaseOrderCreateWindow::~PurchaseOrderCreateWindow()
{
    delete purchaseordercreatewindowUi;
}

void PurchaseOrderCreateWindow::on_submitButton_clicked()
{
    QString medicineName = purchaseordercreatewindowUi->medicineNameLineEdit->text();
    QString supplier = purchaseordercreatewindowUi->supplierLineEdit->text();
    int quantity = purchaseordercreatewindowUi->quantityLineEdit->text().toInt();
    QString purchaseDate = purchaseordercreatewindowUi->purchaseDateEdit->date().toString(Qt::ISODate);

    if (medicineName.isEmpty() || supplier.isEmpty() || quantity <= 0 || purchaseDate == "2020-01-01") {
        QMessageBox::warning(this, "输入错误", "请填写所有必填字段。");
        return;
    }

    QJsonObject orderInfo;
    orderInfo["medicine_name"] = medicineName;
    orderInfo["supplier"] = supplier;
    orderInfo["quantity"] = quantity;
    orderInfo["purchase_date"] = purchaseDate;

    networkManager->createPurchaseOrder(orderInfo);
}

void PurchaseOrderCreateWindow::on_resetButton_clicked()
{
    purchaseordercreatewindowUi->medicineNameLineEdit->clear();
    purchaseordercreatewindowUi->supplierLineEdit->clear();
    purchaseordercreatewindowUi->quantityLineEdit->clear();
    purchaseordercreatewindowUi->purchaseDateEdit->setDate(QDate::currentDate());
}

void PurchaseOrderCreateWindow::handleCreatePurchaseOrderResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {
        QMessageBox::information(this, "成功", "采购订单创建成功！");
        on_resetButton_clicked();
    } else {
        QMessageBox::warning(this, "错误", "采购订单创建失败：" + desc);
    }
}
